const express = require('express');
const dayjs = require('dayjs');

// 导入用来创建JWT字符串的模块
const jsonWebToken = require( 'jsonwebtoken' );

// 导入Customer模型模块
const Customer = require( '../models/customer.js' );
// 导入用于生成惟一ID的模块
const uid = require( '../config/uid.js' )

const router = express.Router();

router.get( '/customer/list' , async (req,resp)=>{
    if( req.user ) {
        let array = await Customer.findAll();
        resp.json( array );
    } else {
        resp.json( [ { id: '' , name: '查询失败' , gender: '' , birthdate: '' } ] );
    }
});

router.get( '/customer' , async (req,resp)=>{
    let id = req.query.id ;
    let array = await Customer.findAll({
        where: {
            id: id ? id : 1
        }
    });
    resp.json( array[ 0 ] );
});

router.post( '/customer' , async (req,resp)=>{
    let c = { ...req.body };
    let count = await Customer.update( c , { where:{ id: c.id } })
    console.log( 'POST: ' , count );
    resp.json( { sucess: true , message: '更新成功' });
});

router.put( '/customer' , (req,resp)=>{
    let name = req.body.name ;
    let gender = req.body.gender ;
    let birthdate = req.body.birthdate ;
    let date = dayjs( birthdate ); // 解析字符串为Date实例

    Customer.create( {
        id: uid.idGenerator() ,
        name:  name ? name : '佚名' ,
        gender: gender ? gender : 'male' ,
        birthdate: date
    } )
    .then( function (p) {
        console.log('created.' + JSON.stringify(p));
        resp.json( { sucess: true , message: '保存成功' });
    } ).catch( function (err) {
        console.log('failed: ' + err);
        resp.json( { sucess: false , message: '保存失败' });
    } );

});

router.delete( '/customer' , async (req,resp)=>{
    let id = req.query.id ;
    let count = await Customer.destroy( {
        where: { id }
    });
    console.log( count );
    resp.json( { sucess: true , message: '删除成功' });
});

router.post( '/customer/sign/in' , async (req,resp)=>{
    let c = await Customer.findOne( { name: req.body.name } );
    // 创建一个纯对象
    let x = Object.create(null);
    // 将 c 对象中的属性复制到 x 对象中
    Object.assign( x , c );
    // 创建JWT字符串
    let s = jsonWebToken.sign( x , 'kaifamiao' , { expiresIn: 3600 } , { algorithm: 'HS256'} );
    // 在JWT之前添加认证方式
    const token = 'Bearer ' + s ;
    // 将token返回给客户端
    resp.json( { status: 'OK' , token: token } );
});

module.exports = router ;